package cn.elves.model.rule.service.engine;

import cn.elves.model.rule.service.rules.RuleFilter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class EngineRulesHolder implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    protected static Map<String, RuleFilter> logicFilterMap = new ConcurrentHashMap<>();


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    @PostConstruct
    public void init() {
        //from db
        Map<String, RuleFilter> ruleFilterMap = applicationContext.getBeansOfType(RuleFilter.class);
        logicFilterMap.putAll(ruleFilterMap);
    }


    public RuleFilter selectRule(String ruleKey) {
        return logicFilterMap.get(ruleKey);
    }

    public Boolean addRule(RuleFilter ruleFilter) {
        if(logicFilterMap.containsKey(ruleFilter.getRuleKey())){
            return false;
        }
        logicFilterMap.put(ruleFilter.getRuleKey(),ruleFilter);
        return true;
    }


}
